String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
        re,
        function($1, $2) {
            return args[$2];
        }
        );
};

String.formatmodel = function(str,model){
    for(var k in model){
        var re = new RegExp("{"+k+"}","g");
        str = str.replace(re,model[k]);
    }
    return str;
}

if(!window["Util"]){
    window["Util"] = {};
}


Util.CONFIG = {
    SQBrdColor: "#072246",
    SQBgColor: "#6bb0c9",
    SQOpacity: 15,
    SQScrollStep: 6,
    
    TextBoxDefaultColor: "#BABABA",
    TextBoxActiveColor:"#000"
}

Util.CACHE = {};

function getClipboardData(){
    window.document.ff_clipboard_swf.SetVariable('str', Util.CACHE.CLIPBOARD_TEXT);
}

function hideMenu(){
    Util.CACHE.CopyBox && Util.CACHE.CopyBox.hide();
}

Util.CopyMsg = function(result){
    if(result){
        alert("内容已复制至剪贴板!");
    }
    else{
        alert("复制失败! 您使用的浏览器不支持复制功能.");
    }
}

/*
*
* 复制
*/
Util.Copy = function(pStr,hasReturn, isdo){
    var result = false;
    //IE
    if(window.clipboardData)
    {
        window.clipboardData.clearData();
        result = window.clipboardData.setData("Text", pStr);
    }
    //FireFox
    else
    {
        if(top.window && !isdo){
            top.window.Util.Copy(pStr,hasReturn, true);
            return;
        }
        Util.CACHE.CLIPBOARD_TEXT = pStr;
        if(!Util.CACHE.CopyBox){
            Util.CACHE.CopyBox = $('<div id="ff_clipborad_swf_box" style="position:absolute;width:220px;padding:8px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;background:#CBCBCB;background:rgba(0, 0, 0, 0.2);overflow:hidden; z-index:99999999999;">'+
                '<div style="padding:6px 10px 10px;background:#FFF;overflow:hidden;">'+
                '<h3 style="height:30px;margin:0;padding:0;overflow:hidden;font-size:14px;"><span style="float:left;line-height:30px;">提示信息</span><a href="javascript:;" style="float:right;width:18px;height:18px;margin-top:5px;line-height:18px;text-align:center;overflow:hidden;font-size:12px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;color:#FFF;background:#A4A4A4;" onclick="'+"$('#ff_clipborad_swf_box').hide();"+'">X</a></h3>'+
                '<div style="position:relative;height:40px;overflow:hidden;line-height:35px;text-align:center;text-decoration:underline;" id="js_ff_copy_box_con">点此复制到剪切板</div>'+
                '</div>'+
                '</div>');
            //创建Flash按钮
            $(document.body).append(Util.CACHE.CopyBox);
        }
        if(document.getElementById('ff_clipboard_swf')){
            $("#ff_clipboard_swf").empty().remove();
        }
        var html = [];
        html.push('<object type="application/x-shockwave-flash" data="/static/js/clipboard.swf" width="200" height="40" style="position:relative;top:-35px;" id="ff_clipboard_swf">');
        html.push('<param name="quality" value="high" />');
        html.push('<param name="allowScriptAccess" value="sameDomain" />');
        html.push('<param name="allowFullScreen" value="true" />');
        html.push('<param name="wmode" value="transparent" />');
        html.push('</object>');
        $("#js_ff_copy_box_con").append(html.join(""));
        Util.Layer.Center(Util.CACHE.CopyBox);
        Util.CACHE.CopyBox.show();
        return;
    }
    if(hasReturn){
        return result;
    }
    else{
        Util.CopyMsg(result);
    }
}

//下拉
Util.DropDown =  (function(){
    var _timeout = 200, _hide_status = "hide_status";
    return {
        Bind: function(st){
            st.Title.bind("click",{
                setting: st
            },function(e){ 
                var setting = e.data.setting;
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
                setting.Title.attr(_hide_status,"0");
                setting.Content.show();
                if(setting.ShowHandler){
                    setting.ShowHandler();
                }
            }).bind("mouseover",{
                setting: st
            },function(e){
                var setting = e.data.setting;
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
                if(setting.IsOverShow){
                    setting.overtimer = window.setTimeout(function(){
                        setting.Title.attr(_hide_status,"0");
                        setting.Content.show();
                        if(setting.ShowHandler){
                            setting.ShowHandler();
                        }
                    },st.Timeout||_timeout);
                }
                if(setting.Title.attr(_hide_status) == "1"){
                    setting.Title.attr(_hide_status,"0");
                }
            }).bind("mouseleave",{
                setting: st
            },function(e){
                var setting = e.data.setting;
                if(setting.timer){
                    window.clearTimeout(setting.timer);
                }
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
                if(setting.Title.attr(_hide_status) == "0"){
                    setting.Title.attr(_hide_status,"1");
                    setting.timer = window.setTimeout(function(){
                        if(setting.Title.attr(_hide_status) == "1"){
                            if(setting.HideHandler){
                                setting.HideHandler();
                            }
                            setting.Content.hide();
                        }
                        window.clearTimeout(setting.timer);
                        delete setting.timer;
                    },st.Timeout||_timeout);
                }
            })
            st.Content.bind("mouseover",{
                setting: st
            },function(e){
                var setting = e.data.setting;
                if(setting.Title.attr(_hide_status) == "1"){
                    setting.Title.attr(_hide_status,"0");
                }
            }).bind("mouseleave",{
                setting: st
            },function(e){
                if($.browser.msie){
                    event.cancelBubble=true;
                }else{
                    e.stopPropagation();
                    e.preventDefault();
                }	//停止冒泡
                var setting = e.data.setting;
                if(setting.timer){
                    window.clearTimeout(setting.timer);
                }
                if(setting.overtimer) window.clearTimeout(setting.overtimer);
                setting.Title.attr(_hide_status,"1");
                setting.timer = window.setTimeout(function(){
                    if(setting.Title.attr(_hide_status) == "1"){
                        if(setting.HideHandler){
                            setting.HideHandler();
                        }
                        setting.Content.hide();
                    }
                    window.clearTimeout(setting.timer);
                    delete setting.timer;
                },st.Timeout||_timeout);
            }).hide();
        }
    }
})();

Util.Load = {
    _download: function(type, code, complete, isremove){
        $(code).bind("load",function(){
            isremove && $(code).remove();
            if(complete) complete();
        })
        if(type != "css"){
            code.onreadystatechange = (function(){
                if(code.readyState == "complete" || code.readyState == "loaded"){
                    //document.body.removeChild(code);
                    isremove && $(code).remove();
                    if(complete) complete();
                }
            });
        }
        document.body.appendChild(code);
    },
    JS: function(url,complete, isremove){
        if(isremove == undefined){
            isremove = true;
        }
        var code = document.createElement("script");
        code.src = url;
        Util.Load._download("script", code, complete, isremove);
    },
    Css: function(url, complete){
        var code = document.createElement("link");
        code.href = url;
        code.rel = "stylesheet";
        code.type = "text/css";
        Util.Load._download("css", code, complete);
        return;
    }
}

/*
	公共函数
*/
Util.Mouse = (function(){
    var _cache = {
        move: {
            x:0,
            y:0,
            eX:0,
            eY:0
        },	//手动层缓存对象
        line: {
            x:0,
            y:0,
            eX:0,
            eY:0
        },	//拖动线缓存对象
        sq: {
            t:0,
            l:0,
            x:0,
            y:0,
            w:0,
            h:0,
            st:0
        }	//框选缓存对象
    },Return = {};

    //获取透明遮罩层
    var GetLayOutBox = function(){
        if(!_cache.LayOutBox){
            _cache.LayOutBox = $('<div style="z-index: 1000000003; display: none;background: none repeat scroll 0 0 black;height: 100%;left: 0;position: absolute;top: 0;width: 100%;filter:alpha(opacity=0);-moz-opacity:0;opacity:0;"><div style="height:100%;width:100%;"></div></div>');
            $(document.body).append(_cache.LayOutBox);
        }
        return _cache.LayOutBox;
    }
    
    Return.GetLayOutBox = GetLayOutBox;

    //移动层，mouseover函数
    var moveBoxFun = function(e){
        //鼠标移动
        if(_cache.move.state){			
            _cache.move.eX = e.screenX;
            _cache.move.eY = e.screenY;
            var lessX = _cache.move.eX - _cache.move.x;
            var lessY = _cache.move.eY - _cache.move.y;
            if(_cache.move.box){
                var t = _cache.move.sT + lessY;
                var l = _cache.move.sL + lessX;
                
                if(t > _cache.move.maxT){
                    if(_cache.move.maxT !== false){
                        t = _cache.move.maxT;
                    }
                }
                else if(t < _cache.move.minT){
                    if(_cache.move.minT !== false){
                        t = _cache.move.minT;
                    }
                }
                if(l > _cache.move.maxL){
                    if(_cache.move.maxL !== false){
                        l = _cache.move.maxL;
                    }
                }
                else if(l < _cache.move.minL){
                    if(_cache.move.minL !== false){
                        l = _cache.move.minL;
                    }
                }
                _cache.move.box.css({
                    left: l + "px",
                    top: t + "px"
                });
            }
            if(e.data.move_callback){
                e.data.move_callback();
            }
            return false;
        }
    }

    /*
		绑定移动函数
		obj
		{
			ClickBox 	--点击的标签
			Box		--移动的层
		}
	*/
    Return.MoveBox = function(obj){
        var outer = obj.Outer;
        var box = obj.Box;
        obj.ClickBox.attr("ws_property","1");
        obj.ClickBox.bind("mousedown",{
            box:box,
            outer:outer,
            callback:obj.Callback, 
            move_callback: obj.MoveCallback
        },function(e){
            if($(this).attr("stop_move")) return;
            
            _cache.MoveLayOut = GetLayOutBox();
            _cache.MoveLayOut.css({
                cursor:"default"
            });
            var lay = ($.browser.msie)? _cache.MoveLayOut : $(window);
            lay.unbind("mousemove").bind("mousemove",{
                move_callback:e.data.move_callback
            },function(e){
                if(_cache.move.state){
                    _cache.MoveLayOut.show();
                }
                moveBoxFun(e);
                return false;
            });
            lay.unbind("mouseup").bind("mouseup",function(e){
                //鼠标按起来
                if(_cache.move.state){
                    _cache.move.state = false;
                    _cache.MoveLayOut.hide();
                    _cache.MoveLayOut.css({
                        cursor:"default"
                    });
                    if($.browser.msie){
                        _cache.MoveLayOut[0].releaseCapture();
                    }
                //return false;
                }
            });
			
            if($.browser.msie){
                _cache.MoveLayOut[0].setCapture();
            }

            _cache.move.state = true;
            _cache.move.box = e.data.box;
            _cache.move.outer = e.data.outer;
            _cache.move.x = e.screenX;
            _cache.move.y = e.screenY;
            _cache.move.eX = e.screenX;
            _cache.move.eY = e.screenY;
            _cache.move.sT = _cache.move.box.offset().top;
            _cache.move.sL = _cache.move.box.offset().left;
            if(_cache.move.outer){
                var oh = _cache.move.outer.height(), ow = _cache.move.outer.width(),
                bh = _cache.move.box.height(), bw = _cache.move.box.width();
                _cache.move.minT = _cache.move.outer.offset().top;
                _cache.move.maxT = _cache.move.outer.offset().top + _cache.move.outer.height() - _cache.move.box.height();
                _cache.move.minL = _cache.move.outer.offset().left;
                _cache.move.maxL = _cache.move.outer.offset().left + _cache.move.outer.width() - _cache.move.box.width();
            }
            else{
                _cache.move.minT = false;
                _cache.move.maxT = false;
                _cache.move.minL = false;
                _cache.move.maxL = false;
            }
			
            if(e.data.callback){
                e.data.callback();
            }

            return false;
        });
        return {
            Disable: function(){
                obj.ClickBox.attr("stop_move","1");
            },
            Enable: function(){
                obj.ClickBox.removeAttr("stop_move");
            }
        }
    }
	
    /*
		绑定移动线
		line: 拖动的线条
		type: 拖动手势 (e-resize：箭头朝左右方向; n-resize：箭头朝上下方向; w-resize:箭头朝右上左下方向; ne-resize:箭头朝右下方向)
	*/
    Return.MoveLine = function(line,type,callback,mousedown){
        line.css({
            cursor:type
        });
        line.bind("mousedown",{
            type:type,
            callback:callback,
            down:mousedown
        },function(e){
            _cache.MoveLayOut = GetLayOutBox();
            _cache.MoveLayOut.css({
                cursor:e.data.type
            });
            var lay = ($.browser.msie)? _cache.MoveLayOut : $(window);
            //绑定事件
            lay.unbind("mousemove").bind("mousemove",{
                callback:e.data.callback
            },function(e){
                if(_cache.line.state){
                    _cache.line.eX = e.screenX;
                    _cache.line.eY = e.screenY;
					
                    if(e.data.callback){
                        e.data.callback(_cache.line);
                    }
                    return true;
                }
            }).unbind("mouseup").bind("mouseup",function(e){
                if(_cache.line.state){
                    _cache.line.state = false;
                    _cache.MoveLayOut.hide();
                    if($.browser.msie){
                        _cache.MoveLayOut[0].releaseCapture();
                    }
                    _cache.MoveLayOut.css({
                        cursor:"default"
                    });
                    return false;
                }
            });
            _cache.MoveLayOut.show();
            if($.browser.msie){
                _cache.MoveLayOut[0].setCapture();
            }
            _cache.line.state = true;
            _cache.line.x = e.screenX;
            _cache.line.eX = e.screenX;
            _cache.line.y = e.screenY;
            _cache.line.eY = e.screenY;
            if(e.data.down){
                e.data.down();
				
            }
			
            return false;
        })
    }

    /****选择框****/
    //选择框事件对象
    var sqEvent = {
        //鼠标移动事件
        move:function(e){
            if(_cache.sq.movestate){
                var eX = e.screenX, eY = e.screenY;
                var lessX = eX - _cache.sq.sX, lessY = eY - _cache.sq.sY;
				
                var w = Math.abs(lessX);
                var h = Math.abs(lessY);
				
                var t = lessY? _cache.sq.sT : _cache.sq.sT + lessY, l = lessX? _cache.sq.sL : _cache.sq.sL + lessX;
                var oH = _cache.sq.outer.height() - 2;
                var oW = _cache.sq.dom.width() - 2;
                var scrollTop = _cache.sq.outer.scrollTop();
                var scrollLeft = _cache.sq.outer.scrollLeft();
                if(lessY < 0){
                    t = t - h;
                }
                if(lessX < 0){
                    l = l - w;
                }
				
                if(t < 0){
                    h += t;
                    t = 0;
                }
                else if(t > 0 && (t - scrollTop + h) > oH){
                    h = oH - t + scrollTop;
                }
				
                if(l < 0){
                    w += l;
                    l = 0;
                }
                else if(l > 0 && (l - scrollLeft + w) > oW){
                    w = oW - l + scrollLeft;
                }
                _cache.sq.box.height(h).css({
                    width: w + "px", 
                    left: l + "px", 
                    top: t + "px"
                });
				
                if(_cache.events.mousemove){
                    var l = _cache.sq.box.offset().left, t = _cache.sq.box.offset().top, w = _cache.sq.box.width(), h = _cache.sq.box.height();
                    _cache.events.mousemove(l, t, l+w, t+h, e.ctrlKey, e);
                }
                if(_cache.sq.box.css("display") == "none"){
                    _cache.sq.box.show();
                }
                return true;
            }
        },
        //mouseup事件
        up: function(e){
            if(_cache.sq.movestate){
                _cache.sq.box.show();
                if(_cache.events.mouseup){
                    var l = _cache.sq.box.offset().left, t = _cache.sq.box.offset().top, w = _cache.sq.box.width(), h = _cache.sq.box.height();
                    _cache.events.mouseup(l, t, l+w, t+h, e.ctrlKey, e);
                }
                _cache.sq.box.hide();
                _cache.sq.movestate = false;
                _cache.sq.x = _cache.sq.y = _cache.sq.w = _cache.sq.h = _cache.sq.t = _cache.sq.l = _cache.sq.st = 0;
                /*if($.browser.msie){
                    _cache.MoveLayOut && _cache.MoveLayOut[0].releaseCapture();
                }
                _cache.MoveLayOut && _cache.MoveLayOut.hide();*/
                return true;
            }
        }
    }

    /*
		拖动选择
	*/
    Return.Square = function(dom, outer, events){
        //绑定所在页事件
        dom.bind("mousedown",{
            outer:outer
        },function(e){
            
            if($(e.target).attr("menu")) return true;
            
            var box = $(this);
            /*if($.browser.msie){
                _cache.MoveLayOut = GetLayOutBox();
                _cache.MoveLayOut.show();
                _cache.MoveLayOut[0].setCapture();
            }
            var lay = ($.browser.msie)? _cache.MoveLayOut : $(window);*/
            var lay = ($.browser.msie)?$(document) : $(window);
            lay.unbind("mousemove").bind("mousemove",sqEvent.move).unbind("mouseup").bind("mouseup",sqEvent.up);
            
            if(!_cache.sq.box){
                _cache.sq.box = $('<div style="position:absolute; top:0; left:0; border:1px solid '+Util.CONFIG.SQBrdColor+'; background:'+Util.CONFIG.SQBgColor+'; filter:Alpha(Opacity='+Util.CONFIG.SQOpacity+'); opacity:0.'+Util.CONFIG.SQOpacity+'; overflow:hidden; display:none; z-index:99999;"></div>');
                //$(document.body).append(_cache.sq.box);
                box.append(_cache.sq.box);
            }
            
            
            _cache.sq.movestate = true;
            _cache.sq.outer = e.data.outer;
            var scrollTop = _cache.sq.outer.scrollTop();
            var scrollLeft = _cache.sq.outer.scrollLeft();
            _cache.sq.sX = e.screenX;
            _cache.sq.sY = e.screenY;
            _cache.sq.w = 0;
            _cache.sq.h = 0;
            _cache.sq.sT = e.clientY - _cache.sq.outer.offset().top + scrollTop;
            _cache.sq.sL = e.clientX - _cache.sq.outer.offset().left + scrollLeft;
            _cache.sq.dom = box;
            _cache.events = !events? {} : events;
            var defaultLen = (!$.browser.msie)? 0 : 1;
            if(box.css("position") == "absolute" || box.css("position") == "relative"){
                _cache.sq.box.width(defaultLen).height(defaultLen).css({
                    top:_cache.sq.sT + "px", 
                    left: _cache.sq.sL + "px"
                });
            }
            else{
                _cache.sq.box.width(defaultLen).height(defaultLen).css({
                    top:(_cache.sq.sT - scrollTop) + "px", 
                    left: _cache.sq.sL + "px"
                });
            }
            _cache.sq.box.show();
            if(_cache.events.mousedown){
                var l = _cache.sq.box.offset().left, t = _cache.sq.box.offset().top, w = _cache.sq.box.width(), h = _cache.sq.box.height();
                _cache.events.mousedown(l, t, l+w, t+h, e.ctrlKey, e);

            }
            _cache.sq.box.hide();
            /*
            if(!$.browser.msie){
                _cache.sq.box.hide();
            }*/
            
            return true;
        });
        
        try{
            if(parent){
                //绑定父框架事件
                $(parent.document).bind("mousemove", sqEvent.move).bind("mouseup", sqEvent.up);
            }
        }catch(e){}
        return {
            Disable: function(){
                if(_cache.sq.movestate){
                    _cache.sq.movestate = false;
                    _cache.sq.box.hide();
                    _cache.sq.x = _cache.sq.y = _cache.sq.w = _cache.sq.h = _cache.sq.t = _cache.sq.l = _cache.sq.st = 0;
                    if($.browser.msie){
                        _cache.MoveLayOut[0].releaseCapture();
                    }
                    _cache.MoveLayOut.hide();
                    return false;
                }
            }
        }
    }
    /****END 选择框****/

    return Return;
})();


//标签控制
Util.Layer = (function(){
    var _cache = {},Return = {};	//缓存类
	
    //最小化
    Return.Min = function(box,mBox,callback){
        if(!_cache.MinBorder){
            _cache.Minborder = $('<div style="z-index:10000000;background: none repeat scroll 0 0 #fff;filter:alpha(opacity=30);-moz-opacity:0.3;opacity:0.3;border:1px soild #ccc;position:absolute;top:0;left0;display:none;"></div>');
            $(document.body).append(_cache.Minborder);
        }
        //mBox.show();
        var w = box.width(), h = box.height(), t = box.offset().top, l = box.offset().left, eT = mBox.offset().top, eL = mBox.offset().left, eW = mBox.width(), eH = mBox.height();
        _cache.Minborder.width(w).height(h).css({
            left:l,
            top:t
        }).show();
        _cache.Minborder.animate({
            width:eW,
            height:eH,
            top:eT,
            left:eL
        },300,function(){
            _cache.Minborder.hide();
        });

        if(callback){
            callback();
        }
    }
	
    /*
	设置标签居中(左右居中，上下1:2)
	
	*/
    Return.Center = function(box,setting){
        var mainBox;
        var cut = 0, t = 0, l = 0;
        if(setting){
            if(setting.Main){
                mainBox = setting.Main;
                t = mainBox.offset().top;
                l = mainBox.offset().left;
            }
            else{
                mainBox = $(window);
            }
            if(setting.Cut != undefined){
                cut = setting.Cut;
            }
        }
        else{
            mainBox = $(window);
        }
		
        var cssT = (mainBox.height() - box.height())/3 + cut + t;
        var cssL = (mainBox.width() - box.width())/2 + cut + l;
        if(cssT < 0){
            cssT = 0;
        }
        if(cssL < 0){
            cssL = 0;
        }
        var st = mainBox.scrollTop();
        if(st){
            cssT += st;
        }
        box.css({
            top: cssT, 
            left: cssL
        });
    }
		
    return Return;
})();


Util.Html = {
    StopPropagation:function(e){
        if($.browser.msie){
            event.cancelBubble=true;
        }else{
            e.stopPropagation();
            e.preventDefault();
        }	//停止冒泡
    }
}

Util.Style = {
    IncludeCss: function(id , url){
        if(!document.getElementById(id)){
            var link = document.createElement("link");
            link.id = id;
            link.rel = "stylesheet";

            link.type = "text/css";

            link.href = url;

            document.getElementsByTagName("head")[0].appendChild(link);
        }
    },
    RemoveCss: function(id){
        var linkBox = $("#" + id);
        linkBox.remove();
    }
}

Util.Override = function(b, n, o){
    var _super = {};
    var _params = [];
    var _arg = arguments;
    if(_arg.length > 3){
        for(var i = 3, len = _arg.length; i < len; i++){
            _params.push(_arg[i]);
        }
    }
    b.apply(n, _params);
    for(var k in n){
        _super[k] = n[k];
    }
    for(var k in o){
        n[k] = o[k];
    }
    return _super;
}

//文本输入框
Util.TextBox = {
    BindDefaultText: function(ele,text){
        if(!ele.value){
            ele.value = text;
            ele.style.color = Util.CONFIG.TextBoxDefaultColor;
        }
        else{
            ele.style.color = Util.CONFIG.TextBoxActiveColor;
        }
        ele.onblur = function(){
            if(ele.value == ""){
                ele.value = text;
                ele.style.color = Util.CONFIG.TextBoxDefaultColor;
            }
            else{
                ele.style.color = Util.CONFIG.TextBoxActiveColor;
            }
        };
        ele.onfocus = function(){
            ele.style.color = Util.CONFIG.TextBoxActiveColor;
            if(ele.value == text){
                ele.value = "";
            }
        };
        ele.GetValue = function(){
            if(ele.value == text){
                return "";
            }
            return ele.value;
        };
        ele.Clear = function(){
            ele.value = "";
            ele.onblur();
        };
        return ele;
    },
    BindSearch: function(input, label, clean){
        var timer;
        var _state = false;
        var checkVal = function(){
            if(_state) return;
            if(input.val() == ''){
                label && label.is(':hidden') && label.show();
                clean && !clean.is(':hidden') && clean.hide();
            }
            else{
                label && !label.is(':hidden') && label.hide();
                clean && clean.is(':hidden') &&clean.show();
            }
        }
        
        var listen = function(){
            if(timer) window.clearTimeout(timer);
            timer = window.setTimeout(function(){
                checkVal();
                listen();
            }, 80);
        }
        checkVal();
        listen();
        
        return {
            Disabled: function(){
                _state = true;
                label.hide();
            },
            Enabled: function(){
                _state = false;
                checkVal();
            }
        }
    },
    FocusEnd: function(ele){
        window.setTimeout(function(){
            if($.browser.msie){
                var pn = ele.value.length;

                var rng = ele.createTextRange();

                rng.moveStart("character",pn);

                rng.collapse(true);

                rng.select();
            }
            else{
                ele.setSelectionRange(ele.value.length, ele.value.length);
                ele.focus();
            }
        },10);
    },
    InsertAtCaret: function(textarea, myValue){
        var $t=$(textarea)[0];
        if (document.selection) {
            textarea.focus();
            var sel = document.selection.createRange();
            sel.text = myValue;
            textarea.focus();
        }
        else if ($t.selectionStart || $t.selectionStart == '0') {
            var startPos = $t.selectionStart;
            var endPos = $t.selectionEnd;
            var scrollTop = $t.scrollTop;
            $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
            textarea.focus();
            $t.selectionStart = startPos + myValue.length;
            $t.selectionEnd = startPos + myValue.length;
            $t.scrollTop = scrollTop;
        }
        else {
            textarea.value += myValue;
            textarea.focus();
        }
    }
}

//字符操作
Util.Text = {
    Cut: function(str,count){
        if(str.length > count){
            return str.substring(0,count/2) + "..." + str.substring(str.length - (count/2),str.length);
        }
        return str;
    },
    GetCount: function(str){
        var len = str.length;
        var reLen = 0;
        for (var i = 0; i < len; i++) { 
            if (/^[\u4e00-\u9fa5]{0,}$/.test(str.substring(i, i+1))) {
                // 全角    
                reLen += 2;
            }
            else {
                if(reLen == 0){
                    reLen++;
                }
                reLen++;
            }
        }
        return reLen; 	
    },
    htmlspecialchars: function(string, quote_style, charset, double_encode) {
        var optTemp = 0,
        i = 0,
        noquotes = false;
        if (typeof quote_style === 'undefined' || quote_style === null) {
            quote_style = 2;
        }
        string = string.toString();
        if (double_encode !== false) { // Put this first to avoid double-encoding
            string = string.replace(/&/g, '&amp;');
        }
        string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	
        var OPTS = {
            'ENT_NOQUOTES': 0,
            'ENT_HTML_QUOTE_SINGLE': 1,
            'ENT_HTML_QUOTE_DOUBLE': 2,
            'ENT_COMPAT': 2,
            'ENT_QUOTES': 3,
            'ENT_IGNORE': 4
        };
        if (quote_style === 0) {
            noquotes = true;
        }
        if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
            quote_style = [].concat(quote_style);
            for (i = 0; i < quote_style.length; i++) {
                // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
                if (OPTS[quote_style[i]] === 0) {
                    noquotes = true;
                }
                else if (OPTS[quote_style[i]]) {
                    optTemp = optTemp | OPTS[quote_style[i]];
                }
            }
            quote_style = optTemp;
        }
        if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
            string = string.replace(/'/g, '&#039;');
        }
        if (!noquotes) {
            string = string.replace(/"/g, '&quot;');
        }
	
        return string;
    }
}


/*
* 文件
*/
Util.File = {
    /**
    * 显示文件大小
    *
    *
    */
    ShowSize:function(bytes, fix){
        bytes = parseInt(Number(bytes));
        var unit = new Array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',
            'DB', 'NB');
        var extension = unit[0];
        var max = unit.length;
        for (var i = 1; ((i < max) && (bytes >= 1024)); i++) {
            bytes = bytes / 1024;
            extension = unit[i];
        }
		
        return Number(bytes).toFixed((fix == undefined)?2:fix) + extension;
    },
    GetInputFilePath: function (ele){  
        if(ele){  
            if (window.navigator.userAgent.indexOf("MSIE")>=1){  
                ele.select();  
                return document.selection.createRange().text;
            }
            else if(window.navigator.userAgent.indexOf("Firefox")>=1){  
                if(ele.files){  
                    return ele.files.item(0).getAsDataURL();  
                }  
                return ele.value;  
            }  
            return ele.value;  
        }  
    },
    FileNameCut: function(file_name){
        var lL = file_name.lastIndexOf(".");
        var pey = file_name.substring(lL);
        var name = file_name.substring(0,lL);
        var flong = Util.Validate.mb_strlen(file_name);
        var plong = Util.Validate.mb_strlen(pey);
        if(flong > 451){
            if(plong > 451){
                pey = pey.substring(0,400);
                if(Util.Validate.mb_strlen(name+pey) > 451){
                    name = name.substring(0,49);
                }
            }
            else{
                var lesslong = flong - plong;
                name = name.substring(0,lesslong - 1);
            }
        }
        return name + pey;
    }
}

Util.Date = {
    GetTimeText:function(num){
        var arr = [3600,60];
        var result = "";
        for(var i = 0,len = arr.length; i < len; i++){
            var item = arr[i];
            if(num >= item){
                var s = (num / item).toFixed(0);
                result += Util.Date._getDoubleText(s) + ":";
                num = num % item;
            }
            else{
                result += "00:";
            }
        }
        result += Util.Date._getDoubleText(num);
        return result;
    },
    GetIMText: function(h,m,s){
        var txt = [];
        if(h < 10){
            txt.push("0" + h);
        }
        else{
            txt.push(h);
        }
        if(m < 10){
            txt.push("0" + m);
        }
        else{
            txt.push(m);
        }
        if(s < 10){
            txt.push("0" + s);
        }
        else{
            txt.push(s);
        }
        return txt.join(":");
    },
    _getDoubleText: function(num){
        if(num.toString().length > 1){
            return num;
        }
        else{
            return "0" + num.toString();
        }
    }
}

/**
* 验证
*/
Util.Validate = {
    _reg:{
        intege:"^-?[1-9]\\d*$",					//整数
        intege1:"^[1-9]\\d*$",					//正整数
        intege2:"^-[1-9]\\d*$",					//负整数
        num:"^([+-]?)\\d*\\.?\\d+$",			//数字
        num1:"^[1-9]\\d*|0$",					//正数（正整数 + 0）
        num2:"^-[1-9]\\d*|0$",					//负数（负整数 + 0）
        decmal:"^([+-]?)\\d*\\.\\d+$",			//浮点数
        decmal1:/^[0-9]*.?\d*$/,                //正浮点数
        decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$", //负浮点数
        decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$",  //浮点数
        decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$", //非负浮点数（正浮点数 + 0）
        decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$", //非正浮点数（负浮点数 + 0）
	
        email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, //邮件
        color:"^[a-fA-F0-9]{6}$",				//颜色
        url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$",	//url
        chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$",					//仅中文
        ascii:"^[\\x00-\\xFF]+$",				//仅ACSII字符
        zipcode:"^\\d{6}$",						//邮编
        mobile:/^(13[0-9]|15[0-9]|14[7|5]|18[0-9])\d{8}$/,				//手机
        ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$",	//ip地址
        notempty:function(value){
            return value.length > 0;
        },						//非空
        picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$",	//图片
        rar:"(.*)\\.(rar|zip|7zip|tgz)$",								//压缩文件
        date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$",					//日期
        qq:"^[1-9]*[1-9][0-9]*$",				//QQ号码
        tel:"^(([0\\+]\\d{2,3}(-)?)?(0\\d{2,3})(-)?)?(\\d{7,8})(-(\\d{3,}))?$",	//电话号码的函数(包括验证国内区号,国际区号,分机号)
        name:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2Da-zA-Z]([\\s.]?[\\u4E00-\\u9FA5\\uF900-\\uFA2Da-zA-Z]+){1,}$", //真实姓名由汉字、英文字母、空格和点组成，不能以空格开头至少两个字
        addressname:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2Da-zA-Z]{1,}$",	//收货人
        username:"^[0-9a-zA-Z_\u0391-\uFFE5]{3,15}$",					//用来用户注册。匹配由数字、26个英文字母中文或者下划线组成的字符串 3-15个字符串之间 
        letter:"^[A-Za-z]+$",					//字母
        letter_u:"^[A-Z]+$",					//大写字母
        letter_l:"^[a-z]+$",					//小写字母
        idcard:"^[1-9]([0-9]{14}|[0-9]{16}[0-9xX])$",	//身份证
        passwrd:"^[\\w-@#$%^&*]{6,20}$"         //密码保证6-20位的英文字母/数字/下划线/减号和@#$%^&*这些符号
    },
    Check: function(type,value){
        if(Util.Validate._reg[type] == undefined){
            alert("Type " + type + " is not in the data");
            return false;
        }
        var reg;
        if(typeof Util.Validate._reg[type] == "string"){
            reg = new RegExp(Util.Validate._reg[type]);
        }
        else if((typeof Util.Validate._reg[type]) == "function"){
            return Util.Validate._reg[type](value);
        }
        else{
            reg = Util.Validate._reg[type];
        }
        return reg.test(value);
    },
    mb_strlen: function(str){
        var offset = 0;
        for(var i=0; i<str.length; i++){
            var string = str.substr(i,1);
            if(escape(string).substr(0,2)=="%u"){
                offset +=3;
            }
            else{
                offset +=1;
            }
        }
        return offset;
    },
    BindForm: function(ele,handler){
        var form = $(ele);
        form.submit(function(){
            if($(this).attr("notvali") == "1"){
                return true;
            }
            var state = true;
            var errorArr = {};
            var checkArr = form.find("[vali]");
            var allArr = {};
            for(var i = 0,len = checkArr.length; i < len; i++){
                var typeArr = $(checkArr[i]).attr("vali").split("|");
                for(var j = 0,jlen = typeArr.length; j < jlen; j++){
                    allArr[i.toString()] = checkArr[i];
                    if(!(Util.Validate.Check(typeArr[j],$(checkArr[i]).val()) ||  ($(checkArr[i]).attr("require") == "0" && $.trim($(checkArr[i]).val()) == ""))){
                        state = false;
                        if(!errorArr[i.toString()]){
                            errorArr[i.toString()] = checkArr[i];
                        }
                        break;
                    }
                    if(typeArr[j] == "notempty"){
                        var min = $(checkArr[i]).attr("min") ? Number($(checkArr[i]).attr("min")) : 0;
                        var max = $(checkArr[i]).attr("max") ? Number($(checkArr[i]).attr("max")) : -1;
                        var count = $.trim(checkArr[i].value).length;
                        if(!(min <= count && (max == -1 || max >= count))){
                            state = false;
                            if(!errorArr[i.toString()]){
                                errorArr[i.toString()] = checkArr[i];
                            }
                        }
                    }
                }
            }
            if(handler && handler.DefaultCallBack){
                handler.DefaultCallBack(allArr);
            }
            if(handler && handler.ErrorCallBack){
                handler.ErrorCallBack(errorArr);
            }	
            if(handler && handler.ReturnCallBack){
                return handler.ReturnCallBack($(this),state);
            }
            else{
                return state;
            }
        });
    },
    CheckDate: function (year, month, day ) {
        var myDate = new Date();
        myDate.setFullYear( year, (month - 1), day );
        return ((myDate.getMonth()+1) == month && day<32); 
    }
};


/*
* Cookie控制
*/
Util.Cookie = {
    get:function(name){
        var cookieValue = "";
        var search = name + "=";
        if (document.cookie.length > 0) {
            offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1)
                    end = document.cookie.length;
                cookieValue = decodeURIComponent(document.cookie.substring(offset, end));
            }
        }
        return cookieValue;
    },
    set:function(name, value, hours){
        var expire = "";
        if (hours != null) {
            if(hours == -1 || value == ''){
                expire = "; expires=-1";
            }
            else{
                expire = new Date((new Date()).getTime() + hours * 3600000);
                expire = "; expires=" + expire.toUTCString();
            }
        }
        document.cookie = name + "=" + encodeURIComponent(value) + expire + '; path=/';
    }
}

;(function(){
    if(window['localStorage']){
        //本地存储
        var storage = (function(){
            var _userId = '', 
            _hour_key="api_h5_hour_key",
            _divide = ":";

            var saveHour = function(key, hour){
                var val = localStorage.getItem(_hour_key);
                if(!val){
                    val = _divide;
                    localStorage.setItem(_hour_key, val);
                }
                var reg = new RegExp(_divide + key + "=.*?" + _divide);
                if(reg.test(val)){
                    val = val.replace(reg, function(){
                        return key + "=" + hour + _divide;
                    });
                }
                else{
                    val += key + "=" + hour + _divide;
                }

                localStorage.setItem(_hour_key, val);
            }

            var clearHour = function(){
                var val = localStorage.getItem(_hour_key);
                if(val && val.length > 1){
                    val = val.substring(1, val.length);
                    var arr = val.split(_divide);
                    var newArr = [];
                    if(arr && arr.length){
                        for(var i = 0, len = arr.length; i < len; i++){
                            var item = arr[i];
                            var itemArr = item.split('=');
                            if(itemArr.length == 2){
                                var key = itemArr[0];
                                var v = itemArr[1];
                                if(Number(v) == -1){
                                    storage.remove(key);
                                    continue;
                                }
                                newArr.push(item);
                            }
                        }

                    }
                    if(newArr.length){
                        localStorage.setItem(_hour_key, _divide + newArr.join(_divide));
                    }
                    else{
                        localStorage.setItem(_hour_key, _divide);
                    }

                }
            }

            return {
                init: function(userId){
                    _userId = userId;
                    clearHour();
                },
                set: function(key, val, hour){
                    var key = _userId + "_" + key;
                    localStorage.setItem(key, val);
                    if(hour == undefined){
                        hour = -1;
                    }
                    saveHour(key, hour);
                },
                get: function(key){
                    var key = _userId + "_" + key;
                    return localStorage.getItem(key);
                },
                remove: function(key){
                    var key = _userId + "_" + key;
                    localStorage.removeItem(key);
                }
            }
        })();
        Util.Cookie =  storage;
    }
})();

Util.Image = {
    Rotate: function(img, num){
        if(num == undefined){
            num = 0;
        }
        
        var deg = num * 90;
        
        if($.browser.msie){
        if(num > 3){
            num = 0;
        }
        }
        
        img.css({
            "-webkit-transform": "rotate("+deg+"deg)",
            "-moz-transform": "rotate("+deg+"deg)",
            "-o-transform": "rotate("+deg+"deg)",
            "filter": "progid:DXImageTransform.Microsoft.BasicImage(Rotation="+num+")"
        });
        
        return num;
    }
};

/**
 * title提示
 */
(function(){
    if(navigator.platform.toString().toLowerCase() != "ipad"){
        var styleTxt = [];
        styleTxt.push('position:absolute;');
        styleTxt.push('height:30px;');
        styleTxt.push('max-width:300px;');
        styleTxt.push('padding:5px 10px 0;');
        styleTxt.push('line-height:30px;');
        styleTxt.push('white-space:nowrap;');
        styleTxt.push('overflow:hidden;');
        styleTxt.push('text-overflow:ellipsis;');
        styleTxt.push('color:#FFF;');
        styleTxt.push('border-radius:20px 20px 3px 3px / 8px 8px 3px 3px;');
        styleTxt.push('background:url(/static/js/popup_title.png) repeat-x center top;');
        styleTxt.push('_background-image:url(/static/js/popup_title.gif);');

        $(document).ready(function(){
            var _popTitle, _popTitleTimer, _popTitleHideTime;

            var showTitleFun = function(el){
                if(_popTitleTimer) window.clearTimeout(_popTitleTimer);
                if(_popTitleHideTime) window.clearTimeout(_popTitleHideTime);


                if(!_popTitle){
                    _popTitle = $('<div style="'+styleTxt.join("")+'display:none;z-index:9999999;"></div>');
                    $(document.body).append(_popTitle);
                }
                var oldHtml = _popTitle.html(),html;
                _popTitle.html(html=el.attr("data_title"));
                if(oldHtml != html){
                    _popTitle.hide();
                }

                _popTitleTimer = window.setTimeout(function(){
                    var w = _popTitle.show().outerWidth(), ew = el.outerWidth(),ww=$(window).width();
                    var l = el.offset().left + (ew/2)-(w/2), t = el.offset().top + el.height() + 3;
                    if(l+w>ww){
                        l = ww-w;
                    }
                    if(l<0) l=0;

                    _popTitle.offset({left: l, top: t}).show();
                }, 100);
            }

            $(document).on({
                mouseenter:function(){
                    showTitleFun($(this));
                },
                mouseleave:function(){
                    if(_popTitleTimer) window.clearTimeout(_popTitleTimer);
                    if(_popTitleHideTime) window.clearTimeout(_popTitleHideTime);
                    _popTitleHideTime = window.setTimeout(function(){
                        if(_popTitle){
                            _popTitle.hide();
                        }
                    }, 100);
                }
            },"[data_title]");
            $(document).on('mousemove', function(e){
                var el = $(e.target);
                if(!$(e.target).attr('data_title') && !$(e.target).parents('[data_title]').length && _popTitle){
                    !_popTitle.is(':hidden') && _popTitle.hide();
                }
            });
        });
    }
})();



;(function($,window){
    Util.compress=function(num){
        var new_num = Number(num);
        return isNaN(new_num) ? num : new_num.toString(36);
    }
    Util.decompress=function(num){
        var new_num = parseInt(num, 36);
        return isNaN(new_num) ? num : new_num;
    }
}(jQuery,window));


;(function(){
    var doc,defaultTitle,timer,title,timer2,ctitle,speed=300;
    function titleScroll() {
        if (ctitle.length <title.length) ctitle += " - " + title;
        ctitle = ctitle.substring(1, ctitle.length);
        doc.title = ctitle.substring(0, title.length);
        timer=setTimeout(titleScroll, speed);
    }
    Util.title={
        init:function(defTitle){
            try{
                doc=window.top.document;
                defaultTitle=defTitle||doc.title;
            }catch(e){
                doc=document;
                defaultTitle=defTitle||doc.title;
            }
        },
        start:function(tit,sp){
            if(tit==title) return;
            title=tit;
            ctitle="";
            speed=sp||speed;
            clearTimeout(timer);
            clearTimeout(timer2);
            titleScroll();
        },
        stop:function(tit){
            clearTimeout(timer);
            title="";
            timer2= setTimeout(function(){
                if(doc){
                    doc.title=tit||defaultTitle;
                }
            },3000);

        }
    }
}());
